package com.example.aigc_education.integration.processor.v1.async;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.aigc_education.common.BusinessException;
import com.example.aigc_education.domain.User;
import com.example.aigc_education.integration.config.RestTemplateUtils;
import com.example.aigc_education.integration.constants.CozeConstant;
import com.example.aigc_education.integration.emuns.CozeAsyncWorkflow;
import com.example.aigc_education.integration.impl.CozeTokenIntegrationImpI;
import com.example.aigc_education.integration.processor.v1.CozeAsyncWFProcessor;
import com.example.aigc_education.integration.request.CozeRequest;
import com.example.aigc_education.integration.request.params.v2.CozeAiTeacherParam;
import com.example.aigc_education.integration.response.CozeResponse;
import com.example.aigc_education.mapper.UserMapper;
import com.example.aigc_education.utils.JsonUtils;
import com.example.aigc_education.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

@Component
@Slf4j
public class CozeAiTeacherAyncWFProcessor extends CozeAsyncWFProcessor<CozeAiTeacherParam> {
    @Override
    public CozeAsyncWorkflow workflowType() {
        return CozeAsyncWorkflow.AI_TEACHER;
    }

    @Override
    protected String workflowId() {
        return workflowType().getWorkflowId();
    }

    @Autowired
    private CozeTokenIntegrationImpI cozeTokenIntegration;

    private static final String COZE_SYNC_WORKFLOW_URL = "/workflow/run";

    @Override
    protected CozeRequest<CozeAiTeacherParam> buildRequest(CozeAsyncPlanRequest request) {
        CozeRequest<CozeAiTeacherParam> cozeRequest = new CozeRequest<>();
        cozeRequest.setParameters(new CozeAiTeacherParam());

        return cozeRequest;
    }

    public CozeResponse executeWorkFlow(CozeAsyncPlanRequest request, User loginUser, String targetLevel) {
        if (request == null || loginUser == null) {
            log.warn("CozeAiTeacherAyncWFProcessor executeWorkFlow error params:{}, user:{}", JsonUtils.toJson(request), JsonUtils.toJson(loginUser));
            throw new BusinessException("参数校验失败");
        }

        CozeAiTeacherParam param = new CozeAiTeacherParam();
        param.setTopic(request.getTopic());
        param.setSubtopic(request.getSubtopic());


        param.setName(loginUser.getUserName());
        param.setStyle(loginUser.getStudyStyle());
        param.setGoal(targetLevel);


        CozeRequest<CozeAiTeacherParam> cozeRequest = new CozeRequest<>();
        cozeRequest.setParameters(param);


        // 设置工作流id 与 是否异步
        cozeRequest.setWorkflowId(workflowId());
        cozeRequest.setAsync(true);

        // 请求头设置
        Map<String, String> headerMap = new HashMap<>();

        String cozeToken = cozeTokenIntegration.getCozeToken();
        headerMap.put("Authorization",String.format("Bearer %s",cozeToken));
        headerMap.put("Content-Type", "application/json");

        // 转换为json对象
        JSONObject jsonObject = (JSONObject) JSON.toJSON(cozeRequest);

        String restResult = Optional.ofNullable(RestTemplateUtils.postHttp(CozeConstant.COZE_URL + COZE_SYNC_WORKFLOW_URL, jsonObject, headerMap))
                .orElseThrow(() -> new BusinessException("请求coze失败"));

        // 将返回结果转换为CozeSyncResponse对象
        return JsonUtils.fromJson(restResult, CozeResponse.class);
    }

    @Override
    protected boolean isParamValid(CozeRequest<CozeAiTeacherParam> request) {
//        CozeAiTeacherParam parameters = request.getParameters();
//        if (parameters == null) {
//            log.error("参数为空");
//            return false;
//        }
//
//        if (parameters.getTopic() == null || parameters.getTopic().trim().isEmpty()) {
//            log.error("主题不能为空");
//            return false;
//        }
//
//        if (parameters.getSubtopic()!= null && parameters.getSubtopic().trim().isEmpty()) {
//            log.error("子主题不能为空");
//            return false;
//        }
//
//        if (parameters.getName() == null || parameters.getName().trim().isEmpty()) {
//            log.error("姓名不能为空");
//            return false;
//        }

        return true;
    }


}

